# -*- coding: utf-8 -*-
import wsgiref.handlers
import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
import sys
from lib.BeautifulSoup import BeautifulSoup
import urllib2

class TianyaAnalyzer:
    def parse(self,url):
        page = urllib2.urlopen(url)
        soup = BeautifulSoup(page,fromEncoding='GB18030')
        ret=soup.find('td',id='pageDivTop')
        #print len(ret)
        
        page.close()
            
        return "!!!!!-"+str(soup.__str__('GB18030'))+"!!!!!!!!!!!!"

class TianyaThreadManger:
    def addThread(self,url):
        pass
    def listThread(self):
        pass


class Thread:
    def finalConstruct(self,url):
        pass            


class MainPage(webapp.RequestHandler):
  def get(self):
    if  self.request.GET.has_key('url'):
        url=self.request.GET['url']
        """
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('%s,%s,Hello, webapp World!' %(__name__,url))
        self.response.out.write('%s'%(sys.path))
        """
        parser = TianyaAnalyzer()
        html=parser.parse(url)
        #html=html.decode('utf-8')
        #html=html.encode('gbk')
        self.response.out.write(html)
        
    else:
        template_values = {
            'code': 10005,
            'reason': "parameter not specified:url"
        }
        path = os.path.join(os.path.dirname(__file__), 'template/error.html')
        #self.response.out.write(path)
        self.response.out.write(template.render(path, template_values))

def main():
    
    application = webapp.WSGIApplication(
                                       [('/addThread', MainPage)],
                                       debug=True)                                       
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()